#include "bigint.h"
#include <stdlib.h>
#include <string.h>

int a2bigint(char *s, bigint *bi)
{
	int ia[10];
	int len = 0;
	char sign = 0;
	char *p;
	int temp = 0;
	int count = 1;
	int i = 0;
	int flag = 0;

	if (*s == '-')
	{
		sign = 1;
		p = s + 1;
	}
	else
	{
		p = s;
	}

	while (*p)
	{
		if (*p > '9' || *p < '0')
		{
			return -1;
		}

		if (!flag)
		{
			if (*p == '0')
			{
				continue;
			}
			flag = 1;
		}

		temp = 10 * temp + (*p - '0');
		if (count++ % 9 == 0)
		{
			ia[len++] = temp;
			temp = 0;
		}
		p++;
	}

	if (temp > 0)
	{
		ia[len] = temp;
	} else
	{
		len--;
	}

	while (len >= 0)
	{
		bi->d[i++] = ia[len--];
	}
	bi->digits = count - 1;
	bi->sign = sign;
	return 0;
}

char* bigint2a(bigint *bi)
{
	char * s = 0;
	char *p;
	if (bi->sign)
	{
		p = s = malloc(bi->digits * sizeof(char) + 2);
		*p++ = '-';
	} 
	else
	{
		p = s = malloc(bi->digits * sizeof(char) + 1);
	}

	int last_int = (bi->digits - 1) / 9;
	int i = last_int;

	while (i >= 0)
	{
		int temp = bi->d[i];
		int inner_i = 0;
		int flag = 0;
		char * stemp = malloc(9 * sizeof(char));
		char *ptemp = stemp;
		while (temp > 0)
		{
			*ptemp++ = (temp % 10) + '0';
			inner_i++;
			temp /= 10;
		}
		// 最后一个就不用补零了。
		if (i != 0)
		{
			while (inner_i++ < 9)
			{
				*ptemp++ = '0';
			}
		}

		*ptemp = '\0';
		int size_inner = strlen(stemp);
		for (inner_i = 0; inner_i < size_inner; inner_i++)
		{
			*p++ = *(stemp + size_inner - 1 - inner_i);
		}
		i--;
	}

	
	*p = '\0';

	return s;
}
